Author: Alexey Romaniuha
Posted: 1/23/2008 12:00:00 PM
Question: How do I search for items created within specified date intervals?
Solution: Here's the sample code on how ranged queries can be peformed in Sitecore using the Lucene engine:
Index index = Factory.GetIndex("system");
Database db = Factory.GetDatabase("master");
Searcher searcher = index.GetSearcher(db);
try
{
Analyzer analyzer = new StandardAnalyzer();
/* query information */
string dateFrom = "20070101120000";
string dateTo = "20080101120000";
string queryString = string.Format("[{0} TO {1}]", dateFrom, dateTo);
/* we're about to search using "created" Lucene field declared in the default "system" index */
string fieldName = "created";
/* parse ranged query using Lucene QueryParser class */
Query query = QueryParser.Parse(queryString, fieldName, analyzer);
/* execute query */
Hits hits = searcher.Search(query);
/* output results */
Response.Write("Total: " + hits.Length() + "<hr/>");
for (int i = 0; i < hits.Length(); i++)
{
Document doc = hits.Doc(i);
Item item = Index.GetItem(doc, db);
if (item != null)
{
Response.Write(string.Format("<b>{0}</b><br/>", item.Paths.FullPath));
foreach (Field field in doc.Fields())
{
Response.Write(field.Name() + ": " + field.StringValue() + "<br/>");
}
Response.Write("<hr/>");
}
}
}
finally
{
searcher.Close(); // Do NOT forget to close the searcher as this may lock index
}
The current example shows how to search for items created within specific date intervals using the default system index of the master database.
Additional information on Lucene query syntax can be found in the following article:
http://lucene.apache.org/java/docs/queryparsersyntax.html
Prev Next